package com.jugheadzhou.gateway.filters;

import com.jugheadzhou.gateway.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 *
 * @author jugheadzhou
 * @date 2021-09-27
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private static String TOKEN_PREFIX = "Bearer";

    private static final String TOKEN_HEADER = "Authorization";

    private static final String IGNORE_RUL = "/user-service/login," +
                                             "/cm-service/common/dict," +
                                             "/kafka-producer/test/save";


    /**
     * TODO 网关权限控制
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        boolean ignore = Arrays.stream(IGNORE_RUL.split(",")).anyMatch(e -> e.equals(path));
        if (ignore){
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst(TOKEN_HEADER);
        try {
            if (token != null && token.startsWith(TOKEN_PREFIX)) {
                token = token.substring(TOKEN_PREFIX.length());
                String username = JwtTokenUtil.getUserNameFromToken(token);
                // 获取用户权限
                if (username != null ) {
                    if (JwtTokenUtil.isTokenExpired(token)) {
                        log.error("登陆过期，请重新登录");
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                    }
                }else {
                    log.error("您使用的用户不存在");
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            }else {
                log.error("请求头不合法");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }catch (Exception e){
            log.error("验证失败：", e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
